package pl.edu.agh.ki.neuralnetwork.layer;

import pl.edu.agh.ki.neuralnetwork.exceptions.NeuronNotConnectedException;
import pl.edu.agh.ki.neuralnetwork.neurons.Bias;
import pl.edu.agh.ki.neuralnetwork.neurons.InnerNeuron;
import pl.edu.agh.ki.neuralnetwork.neurons.Neuron;
import pl.edu.agh.ki.neuralnetwork.neurons.SigmoidalNeuron;

public abstract class BPAbstractLayer extends SimpleLayer<InnerNeuron> {
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < getNeuronsList().size(); i++) {
			sb.append("neuron nr: " + i + "\n");
			int k = 0;
			sb.append("bias " + get(i).getBias());
			for (Double w : get(i).getWeights()) {
				if (!get(i).isBias()) {
					if (k % Math.sqrt(get(i).getWeights().size()) == 0)
						sb.append("\n");
					k++;
					sb.append(String.format("%4.2f ", w));
				}
			}
			sb.append("\n");
		}
		return sb.toString();
	}

	private double der(double x) {
		return SigmoidalNeuron.f(x) * (1 - SigmoidalNeuron.f(x));
	}

	public void modifyWeights(int it, double n, double n2) {
		try {
			for (int i = 0; i < getNeuronsList().size(); i++) {
				SigmoidalNeuron sn = (SigmoidalNeuron) get(i);
				Double error = sn.getError();
				Double der = der(sn.getSum());

				for (Neuron neuron : get(i).getInputNeurons()) {
					Double weight = sn.getWeight(neuron);
					Double input = neuron.getOutput();

					double momentum = 0.0;
					if (it != 1) {
						Double prevWeight = sn.getPrevWeight(neuron);
						momentum = n2 * (weight - prevWeight);
					}
					sn.setWeight(neuron, weight + n * error * input * der
							+ momentum);
					// if(sn.getBias()!=null){
					// Double bias = sn.getBias();
					// if(sn.getPrevBias()!=null){
					// Double prevBias = sn.getPrevBias();
					// momentum = n2*(bias-prevBias);
					// }
					// sn.setPrevBias(bias);
					// sn.setBias(bias+n*error*1*der+momentum);
					// }
				}
			}
		} catch (NeuronNotConnectedException e) {
			e.printStackTrace();
		}
	}

}
